<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>

  var geocoder;
  var map;
  var autocomplete;
  var markers = [];

 function initialize(mapload) {
      document.getElementById("latlng").value="<?=$address->long.','.$address->lat ?>";
      document.getElementById("address").value="<?=$address->address ?>";
      document.getElementById("string").value="<?=$address->google_add ?>";
      document.getElementById("city").value="<?=$address->city ?>";
      document.getElementById("region").value="<?=$address->region ?>";
      // Create an array of styles.
      var styles = [
              {stylers: [{ hue: "#006652" },{ saturation: -20 }]},
              {featureType: "road", elementType: "geometry",stylers:[{ lightness: 30 },{ visibility: "simplified" }] },
              {featureType: "road",elementType: "labels"}
               ];
      var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
      var myLatlng = new google.maps.LatLng(14.586902, 120.98570599999994);
      var mapOptions = {zoom: 15,center: myLatlng,mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
                       }};
      geocoder = new google.maps.Geocoder();
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      map.mapTypes.set('map_style', styledMap);
      map.setMapTypeId('map_style');
      //Search Box location restriction       
      var input = document.getElementById('address');
      var options = {
        componentRestrictions: { country: 'ph' }
    };
    //Autocomplete function
      autocomplete = new google.maps.places.Autocomplete(input, options);
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
        codeAddress(); 
    });

/* Zablan paayos na lng ako dito eto yung logic na para mag default position lng ang mapa kung null pa yung address

 if (<?=$address->address ?> != null) {
  codeaddress();
 }
 else {
  *do nothing
 }

 **Ibig sabihin nyan tatawagin nya lng yung codeAddress() na magcoconvert ng address to coordinates pag may laman lng yung "address"
 pero kung wala  magseset na lng yan sa default coordinates ng mapa yan yung logic dyan.

 Sample lng yang codes di ko alam pag query mo eh.
*/
    }

function codeAddress(AddressToPoints) {

  var iconBase = 'behomebased-ph/Design/Final/Photos/Icon';
  var address = document.getElementById('address').value;
   geocoder.geocode( { 'address': address, 'componentRestrictions':{'country':'ph'}}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            icon: URL + 'img/icons/Marker.png',
            position: results[0].geometry.location,
            draggable:true,
        });

        markers.push(marker);

        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2; 
        document.getElementById("latlng").focus();    
      
        google.maps.event.addListener(marker, 'dragend', function() {
        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2;  
        document.getElementById("latlng").focus(); 
        map.setCenter(coordinates);   

        setTimeout(get, 230);

        function get(){
            document.getElementById('address').value = document.getElementById('string').value;
            }
          setTimeout(get, 230);
      });

      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }

    });

  }

function setAllMap(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
    setAllMap(null);
  }

function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

function codeLatLng(PointsToAddress) {

    var input = document.getElementById('latlng').value;
    var latlngStr = input.split(',', 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    var string;
 
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {

          for (var j=0; j<results.length; j++)
          {

          for (var i=0; i<results[j].address_components.length; i++)
              {
                  if (results[j].address_components[i].types[0] == "locality") {
                          //this is the object you are looking for
                          city = results[j].address_components[i];
                      }
                  if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
                          //this is the object you are looking for
                          region = results[j].address_components[i];
                      }
              }
            }

      string = (results[0].formatted_address);
      document.getElementById("string").value = string;
      document.getElementById("city").value =  city.long_name;
      document.getElementById("region").value =  region.long_name;

       if (document.getElementById("region").value == "Metro Manila")
       {
        (document.getElementById("region").value = "National Capital Region");
       }

      var city_name = city.long_name;
      var length = city_name.length;

      if (city_name.substr(-4, 4) == "City")
          {
            document.getElementById("city").value = city_name.substr(0, length-5);
          }

          else if (city_name.substr(0,7) == "City of")
            {
            document.getElementById("city").value = city_name.substr(8,length);
            }
            
             else { 
             }

          } 
          else {
            alert('No results found');
          }
        
      } 
      else {
      }
    });
  }

function cleartext(){
    document.getElementById("address").value="";
    document.getElementById("latlng").value="";
    document.getElementById("string").value="";
    document.getElementById("city").value="";
    document.getElementById("region").value="";
    deleteMarkers();
  }
  google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div class="row">
  <div class="step-wrapper medium-10 medium-centered large-10 large-centered column">
    <div class="stpy large-12 column">

      <div class="step-statement medium-3 large-4 columns">
        <h5>User Registration</h5>
        <p>Locate your Address to find people nearby you. </p>
      </div>  

      <div class="stepbystep medium-9  large-8 columns">
        <div class="right ui ordered  small steps">
          <div class="animated slideInRight completed step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Basic Information</div>
            </div>
          </div>

          <div class="active step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Address</div>
            </div>
          </div>
          <div class="disabled step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Education</div>
            </div>
          </div>
          <div class="disabled step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Work Experience</div>
            </div>
          </div>         
        </div>
      </div>

      <div class="hr-reg large-12 column"><hr></div>

      <div class="large-12 column">
        <div class=" medium-6 large-6 column">
          <input id="address" type="text" placeholder="Search Address" onClick="cleartext();" size=70>
           <div class="large-8 columns" style="opacity: 0;">
            <input id="latlng" type="text" onfocus="codeLatLng()" onchange="codeLatLng()" size=60 readonly><br>
            <input id="string" type="text" size=60 readonly><br>
            <input id="region" type="text" size=60 readonly><br>
            <input id="city" type="text" size=60 readonly><br>
          </div>
        </div>

        <div class="map-reg medium-6 large-6 columns" style="margin-bottom:1rem;padding:0 2rem 0 2rem;">
          <div id="map-canvas" class="large-12 column" style="background:gray;height:320px;border-radius:.34rem;"></div>     
        </div>
      </div>

      <div class="large-12 column" style="padding:0;margin-top:1rem;">

          <div class="btn-save text-left medium-8 large-8 columns" style="padding:0;">
            <a href="<?=BASE_URI ?>registration/step_1" class="text-left button">Previous</a>     
          </div>
          <div class="btn-save text-right medium-4 large-4 columns" style="padding:0;"> 
            <a id="btnSaveStep2"  class="button">Next</a>
          </div>

      </div>

    </div>
  </div>

</div>



<script>
$(document).ready(function(){
initialize();
});
</script>

<script type="text/javascript">
    function saveStep2(address,longt,lat,google_add,region,city)
    {
        var params = {};
        params['address'] = address;
        params['longt'] = longt;
        params['lat'] = lat;
        params['google_add'] = google_add;
        params['region'] = region;
        params['city'] = city;

      
        return $.ajax({
          url: URL + 'registration/save/step_2',
          type: 'post',
          data: params,
          dataType: 'json'         
        });
    }

    var nextUrl = URL + "registration/step_3";
    var $btnSave = $('#btnSaveStep2');
    
    $btnSave.on('click',function(){
        var address = $('#address').val();
        var latLng = $('#latlng').val();
        var google_address = $('#string').val();
        var region = $('#region').val();
        var city = $('#city').val();
        var longLat = latLng.split(",");
        
        saveStep2(address,longLat[1],longLat[0],google_address,region,city).done(function(result){
            if(result.status == false)
            {
                alert(result.messages);
            }
            else if(result.status == true)
            {
                window.location.replace(nextUrl); 
            }
            else
            {
                alert("Something went wrong.");
            }
        });
        
       
    });
</script>

<style>
body {
  background: #F5F5F5 !important;
  height: 100%;
  overflow: hidden;
}
</style>